//
//  ByCoreToolLocation.m
//  beibei_ios
//
//  Created by pro on 16/6/15.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByCoreToolLocation.h"

#import "CityChooseDataBase.h"

static ByCoreToolLocation *instance;        // 单例类

@implementation ByCoreToolLocation

#pragma mark - 实现单例
+ (instancetype)shareInstance {
    
    static dispatch_once_t onceToken;
    //这个函数中的代码快任务只能执行一次。他是线程安全的。
    dispatch_once(&onceToken, ^{
        instance = [[ByCoreToolLocation alloc] init];
        instance.locationManager = [[CLLocationManager alloc] init];
        instance.geocoder = [[CLGeocoder alloc] init];
        
    });
    return instance;
}
// 实现一些限制方法，限制这个类始终只能创建一个对象，并且此对象不能销毁
+ (id)allocWithZone:(struct _NSZone *)zone {
    
    if (instance == nil) {
        instance = [super allocWithZone:zone];
    }
    return instance;
}

- (void)configLocationService {
    
    /** 未打开定位服务 */
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
    }
    /** 未授权则请求授权 */
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"未授权定位，请求授权");
        [self.locationManager requestWhenInUseAuthorization];
    } else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
        NSLog(@"已授权定位");
    }
}
#pragma mark - location delegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateLocations:(NSArray *)locations {
    
    CLLocation *location = [locations firstObject];             //取出第一个位置
    CLLocationCoordinate2D coordinate = location.coordinate;    //位置坐标
    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    // 如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
}
#pragma mark - 全局方法
- (void)startUpdateLoaction {
    
    // 设置代理
    self.locationManager.delegate = self;
    // 设置定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 定位频率,每隔多少米定位一次
    CLLocationDistance distance = 10.0; // 十米定位一次
    self.locationManager.distanceFilter = distance;
    // 启动跟踪定位
    [self.locationManager startUpdatingLocation];
}


#pragma mark - 局部方法
- (void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    // 反地理编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks firstObject];
        if ([self.delegate respondsToSelector:@selector(locationDidComplete:)]) {
            NSMutableDictionary *tmp = [[NSMutableDictionary alloc] initWithDictionary:placemark.addressDictionary];
            [tmp setObject:[CityChooseDataBase getProvinceID:tmp[@"State"]] forKey:@"StateID"];
            [tmp setObject:[CityChooseDataBase getCityID:tmp[@"City"] provinceID:tmp[@"StateID"]] forKey:@"CityID"];
            [tmp setObject:[CityChooseDataBase getAreaID:tmp[@"SubLocality"] cityID:tmp[@"CityID"]] forKey:@"SubLocalityID"];

            [self.delegate locationDidComplete:[tmp copy]];
        }
        
    }];
}
@end
